<?php

namespace app\common\service\pay\alipay;

use app\common\model\Alipay;
use app\common\service\pay\Base;
use app\common\service\pay\PayInterface;
use app\event\OrderRefundSuccess;
use app\event\PaySuccess;
use app\model\CouponOrder;
use app\model\PayLog;
use think\Exception;
use think\facade\Db;
use think\facade\Log;
use Yansongda\Pay\Pay;

class AliPayBase extends Base  implements PayInterface
{

    public function __construct()
    {
        $this->refund_number = time() . rand(10000, 99999);
    }

    public function pay()
    {
        // TODO: Implement pay() method.
    }

    public function refund()
    {

        if ($this->couponOrder->refund_status != CouponOrder::C_REFUND_STATUS_ING){
            throw new Exception('退款状态不正确');
        }

        $config = new Alipay();
        $config = $config->config;

        $result = Pay::alipay($config)->refund([
            'out_trade_no' =>$this->couponOrder->payLog->out_no,
            'refund_amount' => fen2yuan($this->couponOrder->payLog->real_pay_price),
            'refund_reason' => '订单退款',
        ]);

        if ($result->code != '10000'){
            throw new Exception($result->msg);
        }

        event(new OrderRefundSuccess($this->couponOrder));

        return $result;

    }

    public function notify()
    {
        $pay = new Alipay(0);

        $alipay = Pay::alipay($pay->config);

        Log::info('到了阿里回调');

        Db::startTrans();
        try {
            $data = $alipay->verify(); // 是的，验签就这么简单！
            Log::info('获得流水号：' . $data->trade_no);

            $params = [
                'trade_no' => $data->trade_no,
                'out_trade_no' => $data->out_trade_no,
                'real_pay_price' => yuan2fen($data->total_amount)
            ];


            $notify = new \app\model\Notify([
                'params' => $params,
                'from' => 'alipay',
                'relation_no' => $data->out_trade_no,
            ]);

            $notify->save();


            /** @var PayLog $pay */
            $pay = PayLog::query()
                ->where('out_no', $data->out_trade_no)
                ->find();

            if (empty($pay)) {
                \Yansongda\Pay\Log::error('没有该订单流水号', $data->all());
                return fail('没有该订单流水号');
            }

            $pay->trade_no = $data->trade_no;
            $pay->real_pay_price = yuan2fen($data->total_amount);

            event(new PaySuccess($pay));

            //支付成功处理事件
            $notify->status = \app\model\Notify::STATUS_FINISH;
            $notify->save();

            Db::commit();

        } catch (\think\Exception $exception) {
            Db::startTrans();
            Log::error($exception->getMessage());
            return fail('失败');
        }
        return $alipay->success()->send(); // laravel 框架中请直接 `return $alipay->success()`
    }
}